package cn.edu.dgut.sai;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author Sai
 * Created by Sai on 2019-03-10.
 *
 *
 * 测试：
 * curl -v --cookie "Sai=dgut" http://localhost:8080/webapp-demo/hello
 *
 * curl文档：
 * http://www.ruanyifeng.com/blog/2011/09/curl.html
 *
 */
@WebFilter(filterName = "CookiesFilter")
public class CookiesFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {

        System.out.println(this.getClass());

        try {

            Optional.ofNullable(req.getCookies()).orElseThrow(() -> new RuntimeException("Cookies不能为空"));

            Arrays.stream(req.getCookies())
                    .filter(cookie -> "Sai".equals(cookie.getName()))
                    .filter(cookie -> cookie.getValue().equals("dgut"))
                    .findAny().orElseThrow(() -> new RuntimeException("Cookies错误"));

        } catch (RuntimeException e) {
            // res.sendRedirect("error.html");
            // 返回错误信息
            res.setContentType("text/html;charset=UTF-8");
            res.getWriter().println(e.getMessage());
            // write()方法是异步的，所以用curl命令测试，会显示一行错误信息；在浏览器中测试，会显示两行错误信息
            res.getWriter().write(e.getMessage());
            // 直接返回，http请求就不会到达在过滤器后面的servlet
            return;
        }

        // 必需加这句，才能继续执行过滤器链
        chain.doFilter(req,res);
    }

}
